from flask import Blueprint, request, jsonify, g
from extensions import db
from models import Attendance, Employee, User
from utils import success, error, bad_request, forbidden
from datetime import datetime, date, time
from sqlalchemy import extract
from flask_jwt_extended import jwt_required, get_jwt_identity

# 创建考勤管理API蓝图
attendance_api = Blueprint('attendance_api', __name__, url_prefix='/api/attendances')

# 获取考勤记录列表
@attendance_api.route('/', methods=['GET'])
def get_attendances():
    """获取考勤记录列表"""
    try:
        # 检查用户权限
        current_user_id = g.user_id
        user = g.current_user
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取查询参数
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        status = request.args.get('status')
        
        # 构建查询
        query = Attendance.query
        
        # 普通员工只能查看自己的考勤记录
        if user.role != 'admin':
            # 通过user_id查找对应的employee_id
            employee = Employee.query.filter_by(user_id=current_user_id).first()
            if employee:
                query = query.filter(Attendance.employee_id == employee.id)
            else:
                # 如果没有找到对应的员工记录，返回空结果
                query = query.filter(Attendance.employee_id == -1)

        
        # 按日期范围筛选
        if start_date:
            try:
                start_date_obj = datetime.strptime(start_date, '%Y-%m-%d').date()
                query = query.filter(Attendance.date >= start_date_obj)
            except ValueError:
                return bad_request(msg='开始日期格式错误').to_response()
        
        if end_date:
            try:
                end_date_obj = datetime.strptime(end_date, '%Y-%m-%d').date()
                query = query.filter(Attendance.date <= end_date_obj)
            except ValueError:
                return bad_request(msg='结束日期格式错误').to_response()
        
        # 按状态筛选
        if status:
            query = query.filter(Attendance.status == status)
        
        # 按日期倒序排列
        query = query.order_by(Attendance.date.desc())
        
        # 分页查询
        pagination = query.paginate(
            page=page, 
            per_page=per_page, 
            error_out=False
        )
        
        attendances = []
        for att in pagination.items:
            # 查询员工信息
            employee = Employee.query.get(att.employee_id)
            employee_name = employee.name if employee else '未知'
            
            attendance_data = {
                'id': att.id,
                'name': employee_name,
                'date': att.date.isoformat(),
                'check_in_time': datetime.combine(att.date, att.check_in_time).strftime('%Y-%m-%d %H:%M') if att.check_in_time else None,
                'check_out_time': datetime.combine(att.date, att.check_out_time).strftime('%Y-%m-%d %H:%M') if att.check_out_time else None,
                'status': att.status.lower() if att.status else None,
                'created_at': att.created_at.isoformat(),
                'updated_at': att.updated_at.isoformat()
            }
            attendances.append(attendance_data)
        
        return success(data={
            'attendances': attendances,
            'pagination': {
                'page': pagination.page,
                'per_page': pagination.per_page,
                'total': pagination.total
            }
        }).to_response()
        
    except Exception as e:
        return error(msg=f'获取考勤记录失败: {str(e)}').to_response()


# 员工打卡接口
@attendance_api.route('/check-in', methods=['POST'])
def check_in():
    """员工上班打卡"""
    try:
        # 获取当前用户ID
        current_user_id = g.user_id
        user = g.current_user
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取当前时间（服务器时间）
        today = date.today()
        now = datetime.now().time()
        
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        # 获取前端传递的状态信息，如果没有则默认为'present'
        data = request.get_json()
        status = data.get('status', 'present')
        
        # 通过user_id查找对应的employee_id
        employee = Employee.query.filter_by(user_id=current_user_id).first()
        if not employee:
            return error(code=404, msg='员工信息不存在').to_response()
        
        # 检查今天是否已经打卡
        existing_attendance = Attendance.query.filter_by(
            employee_id=employee.id,
            date=today
        ).first()
        
        if existing_attendance:
            return error(code=400, msg='今天已经打卡，请勿重复打卡').to_response()
        
        # 创建新的考勤记录
        attendance = Attendance(
            employee_id=employee.id,
            date=today,
            check_in_time=now,
            status=status
        )
        db.session.add(attendance)
        
        db.session.commit()
        
        return success(msg='上班打卡成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'上班打卡失败: {str(e)}').to_response()

# 员工下班打卡接口
@attendance_api.route('/check-out', methods=['POST'])
def check_out():
    """员工下班打卡"""
    try:
        # 获取当前用户ID
        current_user_id = g.user_id
        user = g.current_user
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取当前时间（服务器时间）
        today = date.today()
        now = datetime.now().time()
        
        # 检查请求是否为JSON格式
        if not request.is_json:
            return bad_request('请求必须是JSON格式').to_response()
        
        # 获取前端传递的状态信息
        data = request.get_json()
        status = data.get('status')
        
        # 通过user_id查找对应的employee_id
        employee = Employee.query.filter_by(user_id=current_user_id).first()
        if not employee:
            return error(code=404, msg='员工信息不存在').to_response()
        
        # 查找今天的考勤记录
        attendance = Attendance.query.filter_by(
            employee_id=employee.id,
            date=today
        ).first()
        
        if not attendance:
            return error(code=404, msg='未找到今天的签到记录，请先签到').to_response()
        
        # 检查是否已经签退
        if attendance.check_out_time:
            return error(code=400, msg='今天已经签退，请勿重复签退').to_response()
        
        # 更新下班时间
        attendance.check_out_time = now
        # 如果前端传递了状态信息，则更新状态
        if status:
            attendance.status = status
        
        db.session.commit()
        
        return success(msg='下班打卡成功').to_response()
        
    except Exception as e:
        db.session.rollback()
        return error(msg=f'下班打卡失败: {str(e)}').to_response()

# 获取本月考勤状态统计
@attendance_api.route('/monthly-status', methods=['GET'])
@jwt_required()
def get_monthly_status():
    """获取当前用户的本月考勤状态统计"""
    try:
        # 获取当前用户
        current_user_id = int(get_jwt_identity())
        user = User.query.get(current_user_id)
        
        if not user:
            return error(code=401, msg='用户不存在').to_response()
        
        # 获取员工信息
        employee = Employee.query.filter_by(user_id=current_user_id).first()
        if not employee:
            return error(code=404, msg='员工信息不存在').to_response()
        
        # 获取本月考勤记录
        current_month = datetime.now().month
        current_year = datetime.now().year
        
        attendance_records = Attendance.query.filter(
            Attendance.employee_id == employee.id,
            extract('month', Attendance.date) == current_month,
            extract('year', Attendance.date) == current_year
        ).all()
        
        # 统计各种状态
        attendance_days = len([r for r in attendance_records if r.status == 'present'])
        late_count = len([r for r in attendance_records if r.status == 'late'])
        early_count = len([r for r in attendance_records if r.status == 'early'])
        absent_count = len([r for r in attendance_records if r.status == 'absent'])
        
        status_distribution = [
            {"name": "正常出勤", "value": attendance_days},
            {"name": "迟到", "value": late_count},
            {"name": "早退", "value": early_count},
            {"name": "缺勤", "value": absent_count}
        ]
        
        data = {
            "attendance_days": attendance_days,
            "late_count": late_count,
            "status_distribution": status_distribution
        }
        
        return success(data=data).to_response()
        
    except Exception as e:
        return error(msg=f'获取本月考勤状态失败: {str(e)}').to_response()
